<?php
namespace Admin\Model;
use Think\Model;
/**
* FieldModel
*/
class FieldModel extends CommonModel
{
	protected $tableName = 'model_field';
	//字段类型存放路径
	private $fieldPath = '';
	//array(验证字段,验证规则,错误提示,[验证条件,附加规则,验证时间])
	protected $_validate = array(
		array('modelid', 'require', '请选择模型！'),
		array('formtype', 'require', '字段类型不能为空！'),
		array('field', 'require', '字段名称必须填写！'),
		array('field', 'isFieldUnique', '该字段名称已经存在！', 0, 'callback', 1),
		array('name', 'require', '字段别名必须填写！'),
		array('field', '/^[a-z_0-9]+$/i', '字段名只支持英文和_！', 0, 'regex', 3),
		array('isbase', array(0, 1), '是否作为基本信息设置错误！', 0, 'in', 3),
		array('isadd', array(0, 1), '是否前台投稿中显示设置错误！', 0, 'in', 3),
	);
	/**
	 * 验证字段名是否已经存在
	 * @param type $fieldName
	 * @return boolean false已经存在，true不存在
	 */
	public function isFieldUnique($fieldName) {
		if (empty($fieldName)) {
			return true;
		}
		if ($this->where(array('modelid' => $this->modelid, 'field' => $fieldName))->count()) {
			return false;
		}
		return true;
	}
	//初始化
	protected function _initialize() {
		parent::_initialize();
		$this->fieldPath = APP_PATH . 'Admin/Fields/';
	}
	/**
	 * 获取可用字段类型列表
	 * @return array
	 */
	public function getFieldTypeList() {
		$fields = include $this->fieldPath . 'fields.inc.php';
		$fields = $fields? : array();
		return $fields;
	}
	/**
	 * 根据模型ID读取全部字段信息
	 * @param type $modelid 模型ID
	 * @return type
	 */
	public function getModelField($modelid) {
		return $this->where(array("modelid" => $modelid))->order(array("listorder" => "ASC"))->select();
	}
	/**
	 * 添加字段
	 * @param type $data 字段相关数据
	 * @return boolean
	 */
	public function addField($data) {
		//保存一份原始数据
		$oldData = $data;
		//字段附加配置
		$setting = $data['setting'];
		//附加属性值
		$data['setting'] = serialize($setting);
		//模型id
		$modelid = $data['modelid'];
		//完整表名获取 判断主表 还是副表
		$tablearr = M('Model')->where("modelid=$modelid")->field('table')->find();
		$tablename = "model_" . $tablearr['table'];
		if (!$this->table_exists($tablename)) {
			$this->error = '数据表不存在！';
			return false;
		}
		//数据正则
		$pattern = $data['pattern'];
		//进行数据验证
		$data = $this->create($data, 1);
		if ($data) {
			$data['pattern'] = $pattern;
			//检查字段是否存在
			if ($this->field_exists($tablename, $data['field'])) {
				$this->error = '该字段已经存在！';
				return false;
			}
			//根据字段设置临时更改字段类型，否则使用字段配置文件配置的类型
			if (isset($oldData['setting']['fieldtype'])) {
				$field_type = $oldData['setting']['fieldtype'];
			} else {
				$field_type = $oldData['setting']['type'];
			}

			//增加字段
			$field = array(
				'tablename' => C("DB_PREFIX") . $tablename,
				'fieldname' => $data['field'],
				'maxlength' => $data['maxlength'],
				'minlength' => $data['minlength'],
				'defaultvalue' => $setting['defaultvalue'],
				'minnumber' => $setting['minnumber'],
				'decimaldigits' => $setting['decimaldigits'],
			);
			if ($this->addFieldSql($field_type, $field)) {
				$fieldid = $this->add($data);
				if ($fieldid) {
					return $fieldid;
				} else {
					$this->error = '字段信息入库失败！';
					//回滚
					$this->execute("ALTER TABLE  `{$field['tablename']}` DROP  `{$field['fieldname']}`");
					return false;
				}
			} else {
				$this->error = '数据库字段添加失败！';
				return false;
			}
		} else {
			return false;
		}
	}
	/**
	 * 根据字段类型，增加对应的字段到相应表里面
	 * @param type $field_type 字段类型
	 * @param type $field 相关配置
	 * $field = array(
	 *      'tablename' 表名(完整表名)
	 *      'fieldname' 字段名
	 *      'maxlength' 最大长度
	 *      'minlength' 最小值
	 *      'defaultvalue' 默认值
	 *      'minnumber' 是否正整数 和整数 1为正整数，-1是为整数
	 *      'decimaldigits' 小数位数
	 * )
	 */
	protected function addFieldSql($field_type, $field) {
		//表名
		$tablename = $field['tablename'];
		//字段名
		$fieldname = $field['fieldname'];
		//最大长度
		$maxlength = $field['maxlength'];
		//最小值
		$minlength = $field['minlength'];
		//默认值
		$defaultvalue = isset($field['defaultvalue']) ? $field['defaultvalue'] : '';
		//是否正整数 和整数 1为正整数，-1是为整数
		$minnumber = isset($field['minnumber']) ? $field['minnumber'] : 1;
		//小数位数
		$decimaldigits = isset($field['decimaldigits']) ? $field['decimaldigits'] : '';

		switch ($field_type) {
			case "varchar":
				if (!$maxlength) {
					$maxlength = 255;
				}
				$maxlength = min($maxlength, 255);
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` VARCHAR( {$maxlength} ) NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "tinyint":
				if (!$maxlength) {
					$maxlength = 3;
				}
				$minnumber = intval($minnumber);
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` TINYINT( {$maxlength} ) " . ($minnumber >= 0 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "number"://特殊字段类型，数字类型，如果小数位是0字段类型为 INT,否则是FLOAT
				$minnumber = intval($minnumber);
				$defaultvalue = $decimaldigits == 0 ? intval($defaultvalue) : floatval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` " . ($decimaldigits == 0 ? 'INT' : 'FLOAT') . " " . ($minnumber >= 0 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "smallint":
				$minnumber = intval($minnumber);
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` SMALLINT " . ($minnumber >= 0 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "mediumint":
				$minnumber = intval($minnumber);
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` INT " . ($minnumber >= 0 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "int":
				$minnumber = intval($minnumber);
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` INT " . ($minnumber >= 0 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "mediumtext":
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` MEDIUMTEXT";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "text":
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` TEXT";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "date":
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` int";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case "datetime":
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` int";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case "timestamp":
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` int";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case 'readpoint'://特殊字段类型
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` ADD  `readpoint` SMALLINT(5) unsigned NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case "double":
				$minnumber = intval($minnumber);
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` DOUBLE NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "float":
				$minnumber = intval($minnumber);
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` FLOAT NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "bigint":
				$minnumber = intval($minnumber);
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` BIGINT NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "longtext":
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}`  LONGTEXT ";
				if (false === $this->execute($sql)) {
					$this->error = '数据库字段添加失败！';
					return false;
				}
				break;
			case "char":
				$sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}`  CHAR(255) DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case "pages"://特殊字段类型
				$this->execute("ALTER TABLE `{$tablename}` ADD `paginationtype` TINYINT( 1 ) NOT NULL DEFAULT '0'");
				$this->execute("ALTER TABLE `{$tablename}` ADD `maxcharperpage` MEDIUMINT( 6 ) NOT NULL DEFAULT '0'");
				return true;
				break;
			default:
				return false;
				break;
		}
		return true;
	}
	/**
	 *  编辑字段
	 * @param type $data 编辑字段数据
	 * @param type $fieldid 字段id
	 * @return boolean
	 */
	public function editField($data, $fieldid = 0) {
		if (!$fieldid && !isset($data['fieldid'])) {
			$this->error = '缺少字段id！';
			return false;
		} else {
			$fieldid = $fieldid ? $fieldid : (int) $data['fieldid'];
		}
		//原字段信息
		$info = $this->where(array("fieldid" => $fieldid))->find();
		if (empty($info)) {
			$this->error = '该字段不存在！';
			return false;
		}
		//字段主表副表不能修改
		unset($data['issystem']);
		//字段类型
		if (empty($data['formtype'])) {
			$data['formtype'] = $info['formtype'];
		}
		//模型id
		$modelid = $info['modelid'];
		//完整表名获取 判断主表 还是副表
		$tablearr = M('Model')->where("modelid=$modelid")->field('table')->find();
		$tablename = "model_" . $tablearr['table'];
		if (!$this->table_exists($tablename)) {
			$this->error = '数据表不存在！';
			return false;
		}
		//保存一份原始数据
		$oldData = $data;
		//字段附加配置
		$setting = $data['setting'];
		//根据字段设置临时更改字段类型，否则使用字段配置文件配置的类型
		if (isset($oldData['setting']['fieldtype'])) {
			$field_type = $oldData['setting']['fieldtype'];
		} else {
			$field_type = $oldData['setting']['type'];
		}
		//附加属性值
		$data['setting'] = serialize($setting);
		//数据正则
		$pattern = $data['pattern'];
		//进行数据验证
		$data = $this->create($data, 2);
		if ($data) {
			$data['pattern'] = $pattern;
			if (false !== $this->where(array("fieldid" => $fieldid))->save($data)) {
				//如果字段名变更
				if ($data['field'] && $info['field']) {
					//检查字段是否存在，只有当字段名改变才检测
					if ($data['field'] != $info['field'] && $this->field_exists($tablename, $data['field'])) {
						$this->error = '该字段已经存在！';
						//回滚
						$this->where(array("fieldid" => $fieldid))->save($info);
						return false;
					}
					//合并字段更改后的
					$newInfo = array_merge($info, $data);
					$newInfo['setting'] = unserialize($newInfo['setting']);
					$field = array(
						'tablename' => C("DB_PREFIX") . $tablename,
						'newfilename' => $data['field'],
						'oldfilename' => $info['field'],
						'maxlength' => $newInfo['maxlength'],
						'minlength' => $newInfo['minlength'],
						'defaultvalue' => $newInfo['setting']['defaultvalue'],
						'minnumber' => $newInfo['setting']['minnumber'],
						'decimaldigits' => $newInfo['setting']['decimaldigits'],
					);
					if (false === $this->editFieldSql($field_type, $field)) {
						$this->error = '数据库字段结构更改失败！';
						//回滚
						$this->where(array("fieldid" => $fieldid))->save($info);
						return false;
					}
				}
				return true;
			} else {
				$this->error = '数据库更新失败！';
				return false;
			}
		} else {
			return false;
		}
	}
	/**
	 * 执行数据库表结构更改
	 * @param type $field_type 字段类型
	 * @param type $field 相关配置
	 * $field = array(
	 *      'tablename' 表名(完整表名)
	 *      'newfilename' 新字段名
	 *      'oldfilename' 原字段名
	 *      'maxlength' 最大长度
	 *      'minlength' 最小值
	 *      'defaultvalue' 默认值
	 *      'minnumber' 是否正整数 和整数 1为正整数，-1是为整数
	 *      'decimaldigits' 小数位数
	 * )
	 */
	protected function editFieldSql($field_type, $field) {
		//表名
		$tablename = $field['tablename'];
		//原字段名
		$oldfilename = $field['oldfilename'];
		//新字段名
		$newfilename = $field['newfilename'] ? $field['newfilename'] : $oldfilename;
		//最大长度
		$maxlength = $field['maxlength'];
		//最小值
		$minlength = $field['minlength'];
		//默认值
		$defaultvalue = isset($field['defaultvalue']) ? $field['defaultvalue'] : '';
		//是否正整数 和整数 1为正整数，-1是为整数
		$minnumber = isset($field['minnumber']) ? $field['minnumber'] : 1;
		//小数位数
		$decimaldigits = isset($field['decimaldigits']) ? $field['decimaldigits'] : '';

		if (empty($tablename) || empty($newfilename)) {
			$this->error = '表名或者字段名不能为空！';
			return false;
		}

		switch ($field_type) {
			case 'varchar':
				//最大值
				if (!$maxlength) {
					$maxlength = 255;
				}
				$maxlength = min($maxlength, 255);
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` VARCHAR( {$maxlength} ) NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case 'tinyint':
				$minnumber = intval($minnumber);
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` TINYINT " . ($minnumber >= 0 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case 'number'://特殊字段类型，数字类型，如果小数位是0字段类型为 INT,否则是FLOAT
				$minnumber = intval($minnumber);
				$defaultvalue = $decimaldigits == 0 ? intval($defaultvalue) : floatval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` " . ($decimaldigits == 0 ? 'INT' : 'FLOAT') . " " . ($minnumber >= 0 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case 'smallint':
				$minnumber = intval($minnumber);
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` SMALLINT " . ($minnumber >= 0 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case 'mediumint':
				$minnumber = intval($minnumber);
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` MEDIUMINT " . ($minnumber >= 0 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case 'int':
				$minnumber = intval($minnumber);
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` INT " . ($minnumber >= 0 ? 'UNSIGNED' : '') . " NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case 'mediumtext':
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` MEDIUMTEXT";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case 'text':
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` TEXT";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case 'date':
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` int";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case 'datetime':
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` int";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case 'timestamp':
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` int";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case 'readpoint'://特殊字段类型
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `readpoint` SMALLINT(5) unsigned NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case "double":
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` DOUBLE NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case "float":
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` FLOAT NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case "bigint":
				$defaultvalue = intval($defaultvalue);
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}`  BIGINT NOT NULL DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case "longtext":
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}`  LONGTEXT";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			case "char":
				$sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` CHAR(255) DEFAULT '{$defaultvalue}'";
				if (false === $this->execute($sql)) {
					$this->error = '字段结构更改失败！';
					return false;
				}
				break;
			//特殊自定义字段
			case 'pages':
				break;
			default:
				$this->error = "字段类型" . $field_type . "不存在相应信息！";
				return false;
				break;
		}
		return true;
	}
	/**
	 * 删除字段
	 * @param type $fieldid 字段id
	 * @return boolean
	 */
	public function deleteField($fieldid) {
		//原字段信息
		$info = $this->where(array("fieldid" => $fieldid))->find();
		if (empty($info)) {
			$this->error = '该字段不存在！';
			return false;
		}
		//模型id
		$modelid = $info['modelid'];
		//完整表名获取 判断主表 还是副表
		$tablearr = M('Model')->where("modelid=$modelid")->field('table')->find();
		$tablename = "model_" . $tablearr['table'];
		if (!$this->table_exists($tablename)) {
			$this->error = '数据表不存在！';
			return false;
		}
		if ($this->deleteFieldSql($info['field'], C("DB_PREFIX") . $tablename)) {
			$this->where(array("fieldid" => $fieldid, "modelid" => $modelid))->delete();
			return true;
		} else {
			$this->error = '数据库表字段删除失败！';
			return false;
		}
	}
	/**
	 * 根据字段类型，删除对应的字段到相应表里面
	 * @param type $filename 字段名称
	 * @param type $tablename 完整表名
	 */
	protected function deleteFieldSql($filename, $tablename) {
		//不带表前缀的表名
		$noprefixTablename = str_replace(C("DB_PREFIX"), '', $tablename);
		if (empty($tablename) || empty($filename)) {
			$this->error = '表名或者字段名不能为空！';
			return false;
		}

		if (false === $this->table_exists($noprefixTablename)) {
			$this->error = '该表不存在！';
			return false;
		}
		switch ($filename) {
			case 'readpoint'://特殊字段类型
				$sql = "ALTER TABLE `{$tablename}` DROP `readpoint`;";
				if (false === $this->execute($sql)) {
					$this->error = '字段删除失败！';
					return false;
				}
				break;
			//特殊自定义字段
			case 'pages':
				if ($this->field_exists($noprefixTablename, "paginationtype")) {
					$this->execute("ALTER TABLE `{$tablename}` DROP `paginationtype`;");
				}
				if ($this->field_exists($noprefixTablename, "maxcharperpage")) {
					$this->execute("ALTER TABLE `{$tablename}` DROP `maxcharperpage`;");
				}
				break;
			default:
				$sql = "ALTER TABLE `{$tablename}` DROP `{$filename}`;";
				if (false === $this->execute($sql)) {
					$this->error = '字段删除失败！';
					return false;
				}
				break;
		}
		return true;
	}
	public function priviewform($data) {
		$data['setting'] = unserialize($data['setting']);
		if (isset($data['setting']['fieldtype'])) {
			$field_type = $data['setting']['fieldtype'];
		} else {
			$field_type = $data['setting']['type'];
		}
		$value = isset($data["value_info"])?$data["value_info"]:$data["setting"]["defaultvalue"];
		switch ($data['formtype']) {
			case 'author':
				if (!empty($data['css'])) {
					$css = $data['css'];
				} else {
					$css = "layui-input";
				}
				$input = <<<STR
					<div class="layui-input-inline" style="width: {$data['setting']['width']}px;">
					  <input type="text" id="{$data['field']}" name="{$data['field']}" class="{$css}" autocomplete="off" value="{$value}">
					</div>
STR;
				break;
			case "box":
				$options = explode(",", $data['setting']['options']);
				if ($data['setting']['boxtype'] == 'radio' || $data['setting']['boxtype'] == 'checkbox') {
					$width = count($options) * $data['setting']['width'];
					$input = '<div class="layui-input-inline" id="'.$data['field'].'" style="width:'.$width.'px;">';
					foreach ($options as $_k) {
						$v = explode("|", $_k);
						$input .= <<<STR
						<input type="{$data['setting']['boxtype']}" name="{$data['field']}[]" value="{$v[1]}" title="{$v[0]}" class="{$css}">
STR;
					}
					$input .= '</div>';
				} else {
					$input = <<<STR
					<div class="layui-input-inline" style="width: 250px;">
					  <select id="{$data['field']}[]" name="{$data['field']}" size="{$data['setting']['size']}" class="{$css}">
STR;
					foreach ($options as $_k) {
						$v = explode("|", $_k);
						$input .= <<<STR
						<option value="{$v[1]}">{$v[0]}</option>
STR;
					}
					$input .= <<<STR
					  </select>
					</div>
STR;
				}
				break;
			case 'downfile':
				$input = <<<STR
					<input id="{$data['field']}" type="hidden" name="{$data['field']}" value="">
					<a onclick="openurl('{$data['field']}')" class="layui-btn">添加文件</a>
STR;
				break;
			case 'downfiles':
				$input = <<<STR
					<input id="{$data['field']}" type="hidden" name="{$data['field']}" value="">
					<a onclick="openurl('{$data['field']}')" class="layui-btn">添加文件</a>
STR;
				break;
			case 'datetime':
				if (!empty($data['css'])) {
					$css = $data['css'];
				} else {
					$css = "layui-input";
				}
				if ($value) {
					switch ($data['setting']['fieldtype']) {
						case 'date':
							$time = date("Y-m-d",$value);
							break;
						case 'datetime_a':
							$time = date("Y-m-d h:i:s",$value);
							break;
						case 'datetime':
							$time = date("Y-m-d H:i:s",$value);
							break;
						case 'int':
							$time = date($data['setting']['format'],$value);
							break;
						default:
							$time = $value;
							break;
					}
				} else {
					$time = "";
				}
				$input = <<<STR
					<div class="layui-input-inline">
					  <input id="{$data['field']}" type="text" name="{$data['field']}" class="{$css}" autocomplete="off" value="{$time}" onclick="layui.laydate({elem: this, istime: true, format: 'YYYY-MM-DD hh:mm:ss'})">
					</div>
STR;
				break;
			case 'editor':
				$input = <<<STR
					<textarea id="{$data['field']}" style="height:{$data['setting']['height']}px; width:100%;" class="{$css}" name="{$data['field']}">{$value}</textarea>
					<script type="text/javascript" charset="utf-8" src="/Public/kindeditor/kindeditor.js"></script>
					<script type="text/javascript" charset="utf-8" src="/Public/kindeditor/lang/zh_CN.js"></script>
					<script>
						KindEditor.ready(function(K) {
								window.editor = K.create("#{$data['field']}");
						});
					</script>
STR;
				break;
			case 'image':
				if ($value !== NULL && $value !== '') {
					if (strpos($value, ',') !== false) {
						$arr = explode(',', $value);
						foreach ($arr as $key => $val) {
							$path = M('files')->where('id='.$val)->getField('path');
							$imgs .= '<img src="'.$path.'">';
						}
					} else {
						$path = M('files')->where('id='.$value)->getField('path');
						$imgs .= '<img src="'.$path.'">';
					}
				}
				$input = <<<STR
					<input id="{$data['field']}" type="hidden" name="{$data['field']}" value="{$value}">
					<a onclick="openurl('{$data['field']}','image')" class="layui-btn">添加文件</a>
					<div id="div{$data['field']}" class="divimg">{$imgs}</div>
STR;
				break;
			case 'images':
				if ($value !== NULL && $value !== '') {
					if (strpos($value, ',') !== false) {
						$arr = explode(',', $value);
						foreach ($arr as $key => $val) {
							$path = M('files')->where('id='.$val)->getField('path');
							$imgs .= '<img src="'.$path.'">';
						}
					} else {
						$path = M('files')->where('id='.$value)->getField('path');
						$imgs .= '<img src="'.$path.'">';
					}
				}
				$input = <<<STR
					<input id="{$data['field']}" type="hidden" name="{$data['field']}" value="{$value}">
					<a onclick="openurl('{$data['field']}','images')" class="layui-btn">添加文件</a>
					<div id="div{$data['field']}" class="divimg">{$imgs}</div>
STR;
				break;
			case 'number':
				if (!empty($data['css'])) {
					$css = $data['css'];
				} else {
					$css = "layui-input";
				}
				$input = <<<STR
					<div class="layui-input-inline" style="width: {$data['setting']['size']}px;">
					  <input id="{$data['field']}" type="text" name="{$data['field']}" class="{$css}" autocomplete="off" value="{$value}">
					</div>
STR;
				break;
			case 'text':
				if ($data['setting']['ispassword'] == 1) {
					$type = "password";
				} else {
					$type = 'text';
				}
				if (!empty($data['css'])) {
					$css = $data['css'];
				} else {
					$css = "layui-input";
				}
				$input = <<<STR
					<div class="layui-input-inline" style="width: {$data['setting']['size']}px;">
					  <input id="{$data['field']}" type="{$type}" name="{$data['field']}" class="{$css}" autocomplete="off" value="{$value}">

					</div>
STR;
				break;
			case 'textarea':
				$input = <<<STR
					<textarea id="{$data['field']}" name="{$data['field']}" class="{$css}" style="width:{$data['setting']['width']}%; height:{$data['setting']['height']}px;">{$value}</textarea>
STR;
				break;
			case 'omnipotent':
				$input = $data['setting']['formtext'];
				break;
			default:
				return false;
				break;
		}
		$data = <<<DATATOP
		<tr>
		  <td>
		  <label>{$data["name"]}</label>
		  <br>{$data['tips']}
		  </td>
		  <td>
DATATOP;
		$data .= $input;
		$data .= <<<DATAFOOT
		  </td>
		</tr>
DATAFOOT;
		return $data;
	}
}